import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:video_player/video_player.dart';

import '../intent/video_play_state.dart';

class VideoPlayViewModel extends StateNotifier<VideoPlayState> {
  VideoPlayViewModel() : super(VideoPlayState());

  Future<void> initData(String videoName, String videoUrl) async {
    state = state.copyWith(controller: VideoPlayerController.networkUrl(Uri.parse(videoUrl)));

    // 监听播放状态变化
    state.controller!.addListener(() {
      if (state.controller?.value.isInitialized == true && state.isLoading) {
        state = state.copyWith(isLoading: false);
        state.controller!.play();
      }
      if (state.controller!.value.isPlaying != state.isPlaying) {
        state = state.copyWith(isPlaying: state.controller!.value.isPlaying);
      }
      final newPosition = state.controller!.value.position.inSeconds.toDouble();
      if (newPosition != state.sliderValue) {
        state = state.copyWith(sliderValue: newPosition);
      }
    });
    await state.controller!.setLooping(false);
    await state.controller!.initialize();

    startHideTimer();
  }

  void toggleFullScreen() {
    resetHideTimer(); // 重置隐藏计时器
    state = state.copyWith(isFullScreen: !state.isFullScreen);
    if (state.isFullScreen) {
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
      SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
    } else {
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    }
  }

  void seekTo(double value) {
    resetHideTimer(); // 重置隐藏计时器
    final position = Duration(seconds: value.toInt());
    state.controller!.seekTo(position);
    state = state.copyWith(sliderValue: value);
  }

  // 显示/隐藏控制栏
  void toggleControls() {
    print("点击了播放器");
    if (state.showControls) {
      // 如果当前是显示状态，点击则隐藏，并取消定时器
      state = state.copyWith(showControls: false);
      cancelHideTimer();
    } else {
      // 如果当前是隐藏状态，点击则显示，并启动新的定时器
      state = state.copyWith(showControls: true);
      startHideTimer(); // 重新启动计时器
    }
  }

  // 启动隐藏计时器
  void startHideTimer() {
    cancelHideTimer();
    state = state.copyWith(
      hideTimer: Timer(const Duration(seconds: 5), () {
        if (mounted) {
          state = state.copyWith(showControls: false);
        }
      }),
    );
  }

  // 重置隐藏计时器（取消当前计时器并重新开始）
  void resetHideTimer() {
    cancelHideTimer();
    // 操作时确保控制栏显示
    state = state.copyWith(showControls: true);
    startHideTimer(); // 重新启动计时器
  }

  // 取消隐藏计时器
  void cancelHideTimer() {
    state.hideTimer?.cancel();
    state = state.copyWith(hideTimer: null);
  }

  void togglePlayPause() {
    resetHideTimer(); // 重置隐藏计时器
    if (state.controller!.value.isPlaying) {
      state.controller!.pause();
    } else {
      state.controller!.play();
    }
  }

  String formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = twoDigits(duration.inHours);
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    if (duration.inHours > 0) {
      return '$hours:$minutes:$seconds';
    } else {
      return '$minutes:$seconds';
    }
  }
}
